<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="行政区域代码" prop="code" label-width="100px">
        <el-input
          v-model.trim="queryParams.code"
          placeholder="请输入行政区域代码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model.trim="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:region:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:region:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:region:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:region:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="regionList"
      @selection-change="handleSelectionChange"
      row-key="id"
      lazy
      :load="load"
      ref="table"
      :key="forceUpdateKey"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="名称" align="left" prop="name" show-overflow-tooltip/>
      <el-table-column label="行政区域代码" align="center" prop="code"/>
      <el-table-column label="地区ID" align="center" prop="id"/>
      <el-table-column label="父级ID" align="center" prop="parentId"/>
      <el-table-column label="区域祖级列表" align="center" prop="ancestors"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:region:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:region:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      layout="sizes, prev, pager, next, jumper"
    />

    <!-- 添加或修改行政区域管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" ref="editDialog" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="父级区域" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :options="copyRegionDataOptions"
            :normalizer="normalizer"
            placeholder="选择父级区域"
            :loadOptions="loadRegionOptions"
            noOptionsText="暂无选项"
            noResultsText="没有匹配的搜索结果"
          />
        </el-form-item>

        <el-form-item label="区域名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入区域名称"/>
        </el-form-item>

        <el-form-item label="区域代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入区域代码"/>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listRegion, getRegion, delRegion, addRegion, updateRegion, getChildRegion} from "@/api/system/region";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Region",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 行政区域管理表格数据
      regionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: undefined,
        name: undefined,
        parentId: "0",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          {required: true, message: "父级区域不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "区域名称不能为空", trigger: "blur"}
        ],
        code: [
          {required: true, message: "区域代码不能为空", trigger: "blur"},
          {
            pattern: /^[0-9]*$/,
            message: "请输入数字",
            trigger: "blur"
          }
        ],
      },
      // 复制一份地区联动选择器数据，解决树形选择器第一次渲染时卡顿
      copyRegionDataOptions: [],
      //table的key 获取数据时重新渲染表格，解决删除修改懒加载的子节点时刷新有缓存问题
      forceUpdateKey: Math.random()
    };
  },
  computed: {
    // 省份地区联动选择器数据
    regionDataOptions() {
      return this.$store.state.device.regionDataOptions || []
    },
  },
  watch: {
    // 监听vuex地址选项数据改变
    regionDataOptions: {
      handler(newValue) {
        // 先使用第一级数据进行组件渲染展示，第二级以上区域点击省份展开再渲染，节省性能
       const children = newValue.map(item => {
          return {
            ...item,
            children: item.children ? null : undefined,
            leaf: item.children ? false : true,
          }
        })

        // 在所有选项外面加上一个全国选项,解决是省份时parentId为0，修改时因为parentId=0没有数据导致无法自动选中
        this.copyRegionDataOptions = [{
          children: children,
          code: -1,
          id: 0,
          name: '中国',
        }]
      },
      immediate: true
    }
  },
  created() {
    this.getList();
  },
  mounted() {
    /*在页面渲染完后调用dialog实例，将rendered置为true，提前渲染dialog里面内容，
    解决第一次打开弹窗时，由于里面级联选择器数据过多，渲染导致的延迟问题*/
    this.$refs.editDialog.rendered = true;
  },
  methods: {
    // 区域选项加载下面子区域
    loadRegionOptions({parentNode, callback}) {
      if (parentNode.children && parentNode.children.length) return callback && callback();
      parentNode.children = this.regionDataOptions.find(item => {
        return item.id === parentNode.id
      }).children;
      callback && callback();
    },
    /** 转换区域树形图数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    // 点击table下拉加载下属区域
    load(tree, treeNode, resolve) {
      const id = tree.id;

      getChildRegion({id}).then(res => {
        const list = res.rows.map(item => {
          // 区域代码不是12位的话表示还有下一级
          const code = item.code + "";
          return {hasChildren: code.length != 12, ...item}
        });
        resolve(list)

      })
    },
    /** 查询行政区域管理列表 */
    getList() {
      this.loading = true;
      listRegion(this.queryParams).then(response => {
        const list = response.rows.map(item => {
          // 区域代码不是12位的话表示还有下一级
          const code = item.code + "";
          return {hasChildren: code.length != 12, ...item}
        });
        this.forceUpdateKey = Math.random();
        this.regionList = list;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        status: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        parentId: null,
        ancestors: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加行政区域管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRegion(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改行政区域管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const params = {
            name: this.form.name,
            parentId: this.form.parentId,
            id: this.form.id,
            code: this.form.code,
            remark: this.form.remark,
            status: 1
          };
          // console.log("请求参数",params);
          if (this.form.id != null) {
            updateRegion(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList()
              // 更新vuex地区数据
              this.$store.dispatch('LoadRegionDataOptions');
            });
          } else {
            addRegion(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // 更新vuex地区数据
              this.$store.dispatch('LoadRegionDataOptions');
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除行政区域管理编号为"' + ids + '"的数据项？').then(function () {
        return delRegion(ids);
      }).then(() => {
        this.getList();
        // 更新vuex地区数据
        this.$store.dispatch('LoadRegionDataOptions');
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      this.download('system/region/export', {
        ...this.queryParams
      }, `区域管理_${currentDate}.xlsx`)
    }
  }
};
</script>
